#!/usr/bin/perl -w

# Create linked table of contents from a Markdown file.
# Then include the output inside the original <FILE.md>

use strict;
use warnings;
use Getopt::Std;

my %opts = (l => 1, h => 99, s => 0, q => 0);
if (!getopts('l:h:s:aq', \%opts)) {
    goto USAGE;
}

if ($opts{a}) {
    my $line = <STDIN>;
    if (!$line) {
	print STDERR "$0: no standard input: can't parse command\n";
	exit 2;
    }

    chomp $line;
    if ($line =~ /^\s*<!--\s*(.*?)\s*-->\s*$/) {
	print "<!-- $1 -->\n";
	exec $1;
	die "exec '$1' failed: $!";
    } else {
	print STDERR "$0: can't parse command from '$line'\n";
    }
    exit;
}

if (@ARGV == 0) {
  USAGE:
    print STDERR "\
Usage: md2toc [options] <FILE.md>\
        -l <lowest> specifies lowest heading level to include.\
        -h <highest> specifies highest heading level to include.\
        -s <skip> skip the first few lines of generated output.\
	-a specifies automatic mode: run command specified by HTML comment\
	-q question-marks in headings become hyphens in links [false]\n";
    exit 1;
}

my $lowest = $opts{l};
my $highest = $opts{h};
my $skip = $opts{s};

while (my $line = <>) {
    chomp $line;
    if ($line =~ s/^(#+) *//) {
        my $level = length($1);
        next if $level < $lowest || $level > $highest;
        my $link = lc($line);
        $link =~ s/ /-/g;
        $link =~ s/\?/-/g if $opts{q};
        $link =~ s/[^a-z0-9-_]//g;
        if ($skip > 0) {
            $skip--;
        } else {
            print '    ' x ($level-$lowest), "* [$line](#$link)\n";
        }
    }
}
